package com.guyaogg.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guyaogg.common.constant.AuthServerConstant;
import com.guyaogg.common.utils.HttpUtils;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.vo.MemberRespVO;
import com.guyaogg.gulimall.auth.component.GiteeOauthComponent;
import com.guyaogg.gulimall.auth.feign.MemberFeignService;
import com.guyaogg.gulimall.auth.vo.GiteeSocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *
 * @author 顾遥
 */
@Slf4j
@Controller
public class OAuth2Controller {
    private final MemberFeignService memberFeignService;
    private final GiteeOauthComponent giteeOauthComponent;

    public OAuth2Controller(MemberFeignService memberFeignService, GiteeOauthComponent giteeOauthComponent) {
        this.memberFeignService = memberFeignService;
        this.giteeOauthComponent = giteeOauthComponent;
    }

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>(8);
        map.put("client_id", giteeOauthComponent.getClientId());
        map.put("client_secret", giteeOauthComponent.getClientSecret());
        map.put("grant_type", giteeOauthComponent.getGrantType());
        map.put("redirect_uri", giteeOauthComponent.getRedirectUri());
        map.put("code", code);
        // 1. 根据 code 换取 accessToken
        HttpResponse response = HttpUtils.doPost(giteeOauthComponent.getHost(), giteeOauthComponent.getPath(), "post", new HashMap<>(), new HashMap<>(), map);
        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("响应状态码：{},换取的token：{}", statusCode, response);
        // 2. 登录成功跳回首页
        if (statusCode == 200) {
            // 获取到 accessToken
            String json = EntityUtils.toString(response.getEntity());
            GiteeSocialUser socialUser = JSON.parseObject(json, GiteeSocialUser.class);
            log.debug("获取数据对象：{}", socialUser);
//            为当前用户生成一个社交用户，以后这个社交账号对应指定的会员
            // 登录或注册用户，第一次为注册
            R r = memberFeignService.oauth2GiteeLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVO vo = r.getData(new TypeReference<MemberRespVO>() {
                });
                // TODO 1.默认发的令牌。 session=Nm... 作用域：当前域，（解决子域 session 共享问题）
                // TODO 2.希望使用 json 格式存储到 redis 中
                session.setAttribute(AuthServerConstant.LOGIN_USER, vo);
                return "redirect:http://gulimall.com";

            }

        }
        return "redirect:http://auth.gulimall.com/login.html";


    }
}
